package com.example.petadopt.ui.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.petadopt.R;
import com.example.petadopt.common.Result;
import com.example.petadopt.dao.AdoptDao;
import com.example.petadopt.dao.CollectDao;
import com.example.petadopt.dao.PetDao;
import com.example.petadopt.entity.Adopt;
import com.example.petadopt.entity.Collect;
import com.example.petadopt.entity.Pet;
import com.example.petadopt.utils.CurrentUserUtils;
import com.gzone.university.utils.GlideUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 宠物详情页面
 */
public class PetDetailActivity extends AppCompatActivity {

    private ImageView ivPetImage;
    private ImageView ivBack;
    private ImageView ivFavorite;
    private TextView tvPetName;
    private TextView tvGender;
    private TextView tvAge;
    private TextView tvWeight;
    private TextView tvAddress;
    private TextView tvBreed;
    private TextView tvHairColor;
    private TextView tvCharacter;
    private TextView tvHobby;
    private LinearLayout llHealthStatus;
    private Button btnAdopt;

    private Pet pet;
    private Long petId;
    private Long userId; // 当前登录用户ID

    private boolean isAdmin = false; // 是否为管理员

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pet_detail);

        // 获取传递的宠物ID
        petId = getIntent().getLongExtra("pet_id", -1);
        if (petId == -1) {
            Toast.makeText(this, "宠物信息获取失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 获取是否为管理员
        isAdmin = getIntent().getBooleanExtra("is_admin", false);

        // 获取当前登录用户ID
        userId = CurrentUserUtils.getCurrentUser().getId();

        // 初始化视图
        initView();
        // 初始化监听器
        initListener();
        // 加载宠物数据
        loadPetData();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        ivPetImage = findViewById(R.id.iv_pet_image);
        ivBack = findViewById(R.id.iv_back);
        ivFavorite = findViewById(R.id.iv_favorite);
        tvPetName = findViewById(R.id.tv_pet_name);
        tvGender = findViewById(R.id.tv_gender);
        tvAge = findViewById(R.id.tv_age);
        tvWeight = findViewById(R.id.tv_weight);
        tvAddress = findViewById(R.id.tv_address);
        tvBreed = findViewById(R.id.tv_breed);
        tvHairColor = findViewById(R.id.tv_hair_color);
        tvCharacter = findViewById(R.id.tv_character);
        tvHobby = findViewById(R.id.tv_hobby);
        llHealthStatus = findViewById(R.id.ll_health_status);

        btnAdopt = findViewById(R.id.btn_adopt);
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        // 返回按钮
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 收藏按钮
        ivFavorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleFavorite();
            }
        });

        // 申请领养按钮
        btnAdopt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog dialog = new AlertDialog.Builder(PetDetailActivity.this)
                        .setTitle("申请领养")
                        .setMessage("确定申请领养该宠物吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                applyForAdoption();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .create();
                dialog.show();
            }
        });
    }

    /**
     * 加载宠物数据
     */
    private void loadPetData() {
        // 使用userId加载宠物数据，关联用户收藏状态
        Result<Pet> result = PetDao.getPetById(petId, userId);
        if (result.isSuccess() && result.getData() != null) {
            pet = result.getData();
            updateUI();
        } else {
            Toast.makeText(this, "宠物信息加载失败: " + result.getMessage(), Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    /**
     * 更新UI显示
     */
    private void updateUI() {
        // 设置宠物图片
        if (!TextUtils.isEmpty(pet.getImage())) {
            GlideUtils.load(ivPetImage, pet.getImage());
        }

        if (isAdmin) {
            btnAdopt.setVisibility(View.GONE);
            ivFavorite.setVisibility(View.GONE);
        }

        // 根据收藏状态设置收藏图标
        if (pet.getIsCollected() != null && pet.getIsCollected()) {
            ivFavorite.setImageResource(R.drawable.ic_heart);
            ivFavorite.setColorFilter(getResources().getColor(R.color.red_500));
        } else {
            ivFavorite.setImageResource(R.drawable.ic_heart);
            ivFavorite.setColorFilter(getResources().getColor(R.color.gray_800));
        }

        if (pet.getIsAdopted() != null && pet.getIsAdopted()) {
            // 如果宠物已被领养，设置按钮不可点击
            btnAdopt.setEnabled(false);
            btnAdopt.setText("已被领养");
        } else {
            // 如果宠物未被领养，设置按钮可点击
            btnAdopt.setEnabled(true);
            btnAdopt.setText("申请领养");
        }

        // 设置宠物基本信息
        tvPetName.setText(pet.getName());
        tvGender.setText(pet.getGender());
        tvAge.setText(pet.getAge() + "岁");
        tvWeight.setText(pet.getWeight() + "kg");
        tvAddress.setText(pet.getAddress());
        tvBreed.setText(pet.getBreed());
        tvHairColor.setText(pet.getHairColor());
        tvCharacter.setText(pet.getCharacter());
        tvHobby.setText(pet.getHobby());

        // 设置健康状况
        llHealthStatus.removeAllViews();
        List<String> healthStatus = pet.getHealthStatus();
        if (healthStatus != null && !healthStatus.isEmpty()) {
            for (String status : healthStatus) {
                View itemView = createHealthStatusItem(status);
                llHealthStatus.addView(itemView);
            }
        }
    }

    /**
     * 创建健康状况项
     */
    private View createHealthStatusItem(String status) {
        View view = getLayoutInflater().inflate(R.layout.item_health_status, null);
        TextView tvStatus = view.findViewById(R.id.tv_health_status);
        tvStatus.setText(status);
        return view;
    }

    /**
     * 切换收藏状态
     */
    private void toggleFavorite() {
        if (userId == -1) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        if (pet == null || pet.getId() == null) {
            Toast.makeText(this, "宠物信息获取失败", Toast.LENGTH_SHORT).show();
            return;
        }

        boolean isCurrentlyCollected = pet.getIsCollected() != null && pet.getIsCollected();

        if (isCurrentlyCollected) {
            // 如果已收藏，则取消收藏
            Result<Void> result = CollectDao.deleteCollectByUserAndPet(userId, pet.getId());
            if (result.isSuccess()) {
                pet.setIsCollected(false);
                ivFavorite.setImageResource(R.drawable.ic_heart);
                ivFavorite.setColorFilter(getResources().getColor(R.color.gray_800));
                Toast.makeText(this, "已取消收藏", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "取消收藏失败: " + result.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } else {
            // 如果未收藏，则添加收藏
            Collect collect = new Collect();
            collect.setPetId(pet.getId());
            collect.setCollectUserId(userId);
            // 使用当前时间作为收藏时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            collect.setCollectTime(sdf.format(new Date()));

            Result<Void> result = CollectDao.addCollect(collect);
            if (result.isSuccess()) {
                pet.setIsCollected(true);
                ivFavorite.setImageResource(R.drawable.ic_heart);
                ivFavorite.setColorFilter(getResources().getColor(R.color.red_500));
                Toast.makeText(this, "已添加到收藏", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "添加收藏失败: " + result.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 申请领养
     */
    private void applyForAdoption() {
        if (userId == -1) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        if (pet == null || pet.getId() == null) {
            Toast.makeText(this, "宠物信息获取失败", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查宠物是否已被领养
        if (pet.getIsAdopted() != null && pet.getIsAdopted()) {
            Toast.makeText(this, "该宠物已被领养", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建领养记录
        Adopt adopt = new Adopt();
        adopt.setPetId(pet.getId());
        adopt.setAdoptUserId(userId);
        // 使用当前时间作为领养时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        adopt.setAdoptTime(sdf.format(new Date()));

        Result<Void> result = AdoptDao.addAdopt(adopt);
        if (result.isSuccess()) {
            pet.setIsAdopted(true);
            pet.setAdoptUserId(userId);
            btnAdopt.setEnabled(false);
            btnAdopt.setText("已被领养");
            Toast.makeText(this, "领养成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "领养申请失败: " + result.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
} 